$(function() {
    //从缓存中获取数据（在登录成功后会将当前用户和用户令牌放入缓存中）
    const user = JSON.parse(window.sessionStorage.getItem("user"));
    const token = window.sessionStorage.getItem("token");
    if(user == null || token == null){
        alert("请先登录");
        window.location.href = "../html/welcome.html";
    }

    //初始化图片信息
    getAllPicture(token);

    //预览图片
    $("#imgInput").change(function(){
        $("#pictureImg").attr("src",URL.createObjectURL($(this)[0].files[0]));
    });

    //给外部修改按钮添加点击事件
    let url = "http://localhost:2081/picture/one?id=";
    for (let i = 1; i <= 3; i++) {
        $("#updatePictureBtn"+i).click(function (){
            //先清空数据
            $("#pictureId").empty();
            $("#pictureTitle").empty();
            $("#pictureContent").empty();
            $("#pictureImg").removeAttr("src");

            $("#pictureId").html($("#pictureId"+i).text());
            $("#pictureTitle").val($("#title"+i).text());
            $("#pictureContent").val($("#content"+i).text());
            const afterUrl = url+i;
            $("#pictureImg").attr("src",afterUrl.replace(/\"/g, ""));
        });
    }

    //给保存轮播图更改按钮添加点击事件
    $("#savePictureChangeBtn").click(function (){
        const formData = new FormData();
        formData.append("pictureId", $("#pictureId").text());
        formData.append("title", $("#pictureTitle").val());
        formData.append("content", $("#pictureContent").val());
        formData.append("pictureFile", $("#imgInput")[0].files[0]);

        postPicture(token,formData);
    });

    //获取公告栏数据
    getAllNotice(token);

    //给外部的修改按钮添加点击事件
    for (let i = 1; i <= 5; i++) {
        $("#updateNoticeBtn"+i).click(function (){
            //先清空数据
            $("#noticeId").empty();
            $("#noticeTitle").val("");
            $("#noticeContent").val("");

            $("#noticeId").html($("#noticeNum"+i).text());
            $("#noticeTitle").val($("#noticeTitle"+i).text());
            $("#noticeContent").val($("#noticeContent"+i).text());
        });
    }

    //给公告保存按钮添加点击事件
    $("#saveNoticeChangeBtn").click(function (){
        const id = $("#noticeId").text();
        const content = $("#noticeContent").val();
        console.log("内容="+content);

        const notice = new Notice(id,content);

        updateNotice(token,notice);
    });

    //关闭页面时调用logout方法，退出当前登录用户
    $(window).unload(function(){
        $.ajax({
            type:"POST",
            contentType:"application/json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            url :"http://localhost:2082/logout?username=" + user.username
        })
    });
});


//预览图片
function fn_browse()
{
    document.picture_form.browse.click();
    document.picture_form.file.value = document.all.picture_form.browse.value;
}

//上传的图片对象ajax
function postPicture(token,formData){
    $.ajax({
        url: "http://localhost:2082/picture",
        type: "PUT",
        headers: {
            "token":token
        },
        data: formData,
        cache: false,
        processData: false,
        contentType: false,
        success: function (data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                $('#addTucao').modal('hide');
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                if(result.code == 200){
                    $("#changePictureSource").modal('hide');
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "success",
                        autoclose: 2000
                    });
                    getAllPicture(token);
                }else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "failed",
                        autoclose: 2000
                    });
                }
            }
        }
    });
}

//获取所有图片数据ajax
function getAllPicture(token){
    $.ajax({
        contentType: "application/json",
        url: "http://localhost:2082/picture/all",
        type: "GET",
        headers: {
            "token":token
        },
        success: function (data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                $('#addTucao').modal('hide');
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    const pictureData = result.data;
                    for (let i = 1; i <= 3; i++) {
                        const title = JSON.stringify(pictureData[i-1].title);
                        const content = JSON.stringify(pictureData[i-1].content);
                        const pictureId = JSON.stringify(pictureData[i-1].id);
                        //先清空
                        $("#title"+i).empty();
                        $("#content"+i).empty();
                        $("#pictureId"+i).empty();
                        //再赋值
                        $("#title"+i).html(title.replace(/\"/g, ""));
                        $("#content"+i).html(content.replace(/\"/g, ""));
                        $("#pictureId"+i).html(pictureId.replace(/\"/g, ""));
                    }
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }

        }
    });
}

//获取所有公告栏数据ajax
function getAllNotice(token){
    $.ajax({
        type: "GET",
        contentType: "application/json",
        url: "http://localhost:2082/notice",
        headers: {
            "token":token
        },
        success: function (data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    const NoticeData = result.data;
                    for (let i = 1; i <= 5; i++) {
                        const notice = JSON.stringify(NoticeData[i-1].notice);
                        const id = JSON.stringify(NoticeData[i-1].id);
                        //先清空
                        $("#noticeContent"+i).empty();
                        $("#noticeNum"+i).empty();
                        //再赋值
                        $("#noticeContent"+i).html(notice.replace(/\"/g, ""));
                        $("#noticeNum"+i).html(id.replace(/\"/g, ""));
                    }
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }

        }
    });
}

//公告实体类
function Notice(id,notice){
    this.id= id;
    this.notice = notice;
}

//修改公告栏数据ajax
function updateNotice(token,notice){
    $.ajax({
        type: "PUT",
        contentType: "application/json",
        url: "http://localhost:2082/notice",
        headers: {
            "token":token
        },
        data: JSON.stringify(notice),
        success: function (data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    $("#changeNoticeSource").modal('hide');
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "success",
                        autoclose: 2000
                    });
                    //再次分页
                    getAllNotice(token);
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }

        }
    });
}